import React, { useState, useEffect } from "react";
import { Spin, Input } from "antd";
import { PlusOutlined, MinusOutlined } from "@ant-design/icons";
import { easeTab } from "@/layouts/tab";
import './style.less';
import ary from "./data";

const icon = 'https://yfb-fdd-item-icons.oss-ap-southeast-1.aliyuncs.com/opshields/67c46abd-eb54-44c2-9ed8-8cd916ac74a2.32_32.png';

const TabChrome: React.FC = () => {
    const initUrl = `${import.meta.env.VITE_APP_OPSHIELDS_URL}/account-login`;
    const iIdUrlMap = new Map();
    const [activeID, setActiveID] = useState<string>('init_view_content_id');
    const [currentUrl, setCurrentUrl] = useState<string>(initUrl);
    
    // 初始化需要的数据请求
    useEffect(() => {
        console.log('TabChrome', easeTab)
        easeTab.init({
            container: "#Tab",
            initTabs: [{
                id: "init_view_content_id",
                title: 'opshields',
                icon,
            }]
        });
        iIdUrlMap.set('init_view_content_id', initUrl)
        console.log('initUrl', initUrl)
        // 添加tab
        easeTab.on("add", (tab) => {
            // setActiveID(tab.id);
            // setCurrentUrl(tab.url);
            window.electronAPI?.toAdd({ tab });
        });

        easeTab.on("change", ({ focusTab }) => {
            console.log('change', focusTab)
            setActiveID(focusTab.id);
            const url = iIdUrlMap.get(focusTab.id)
            setCurrentUrl(url);
            window.electronAPI?.switchTab2({ focusId: focusTab.id });
        });

        easeTab.on("remove", ({ focusTab, removeTab }) => {
            setCurrentUrl(focusTab.url);
            window.electronAPI?.toRemove({ focusId: focusTab.id, removeId: removeTab.id });
        });

        window.addEventListener('tabAdd', ({ detail }: any) => {
            const { favicon, ...others } = detail;
            setActiveID(detail.id);
            setCurrentUrl(detail.url);
            easeTab.addTab({
                ...others,
                icon: favicon
            });
        })
    }, []);

    const addTab = async (record) => {
        const { id, remark, platformIcon, ...others } = record;
        // setActiveID(id);
        // setCurrentUrl(record.platformUrl);
        // easeTab.addTab({
        //     ...others,
        //     title: remark,
        //     icon: platformIcon
        // });
        
        window && window.dispatchEvent(new CustomEvent("tabAdd", {detail: {
            id,
            url: record.platformUrl,
            title: remark,
            favicon: platformIcon
        }}));
    }

    window.addEventListener('changeUrl', async (e: any) => {
        try {
            const { id , url } = e.detail;
            console.log('changeUrl', id, url, activeID)
            iIdUrlMap.set(id, url);
            if (activeID === id) {
                setCurrentUrl(url)
            }
        } catch (e) {
            console.log('changeUrl error', e)
        }
    })

    const zoomIn = () => {
        window.electronAPI?.zoomIn();
    }

    const zoomOut = () => {
        window.electronAPI?.zoomOut();
    }

    const goBack = () => {
        window.electronAPI?.goBack();
    }

    const goForward = () => {
        window.electronAPI?.goForward();
    }

    const reload = () => {
        window.electronAPI?.reload();
    }

    const urlChangeHandler = (e) => {
        setCurrentUrl(activeID === 'init_view_content_id' ? currentUrl : e.target.value)
    }

    const onPressEnter = (e) => {
        const url = e.target.value;
        setCurrentUrl(url)
        iIdUrlMap.set(activeID, url);
        window.electronAPI?.goto(url);
    }

    
    return (
        <div className="tab-container">
            <div id="Tab"></div>
            <div className="bars">
                <div className="bar address-bar">
                    <div className="tabs-right-buttons">
                        <div className="back-button button" onClick={goBack} />
                        <div className="go-forward-button button" onClick={goForward} />
                        <div className="reload-button button" onClick={reload} />
                    </div>
                    <Input
                        className="address"
                        value={currentUrl}
                        onChange={urlChangeHandler}
                        onPressEnter={onPressEnter}
                        size="small"
                    />
                    <div className="tabs-right-buttons">
                        <PlusOutlined className="button" onClick={zoomIn} />
                        <MinusOutlined className="button" onClick={zoomOut} />
                    </div>
                </div>
            </div>
            <ul>
                {
                    ary.map((item) => {
                        return (
                            <li onClick={() => addTab(item)} key={item.platformName}>{item.remark}</li>
                        )
                    })
                }
                
            </ul>
            <Spin>
                <div style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
                    加载中...Loading...
                </div>
            </Spin>
        </div>
    );
};

export default TabChrome;
